package Leetcode;

import java.util.*;

/**
 * @ Author     ：侯耀祖
 * @ Description：
 */
public class canFinish {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        Map<Integer, List<Integer>> graph = new HashMap<>();
        int[] indgree = new int[numCourses];
        for (int i = 0; i < numCourses; i++) {
            graph.put(i, new ArrayList<>());
        }
        for (int[] prerequisite : prerequisites) {
            graph.get(prerequisite[1]).add(prerequisite[0]);
            indgree[prerequisite[0]]++;
        }
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < numCourses; i++) {
            if (indgree[i] == 0){
                queue.offer(i);
            }
        }
        int count = 0;
        while (!queue.isEmpty()){
            Integer node = queue.poll();
            count++;
            for (Integer next : graph.get(node)) {
                indgree[next]--;
                if (indgree[next] == 0){
                    queue.offer(next);
                }
            }
        }
        return count == numCourses;
    }
}
